package com.hua.yuan.live.repertory.cloud_data.loader;
import android.support.annotation.NonNull;
import android.support.v4.app.LoaderManager;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hua.yuan.common.https.OkHttpModule;
import com.hua.yuan.live.repertory.cloud_data.JsonResult;
import com.hua.yuan.live.repertory.cloud_data.api.LivePlayApi;
import com.hua.yuan.live.repertory.cloud_data.api.LiveVideoListApi;
import com.hua.yuan.live.repertory.cloud_data.res.LiveHistoryComband;
import com.hua.yuan.live.repertory.cloud_data.res.LiveVideoBean;
import com.hua.yuan.live.repertory.cloud_data.res.ResultBean;
import com.hua.yuan.live.repertory.cloud_data.res.ResultMsg;

import java.io.IOException;
import java.util.List;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;
import retrofit2.Response;
/**
 * 直播历史页面
 */
public class LiveHistoryLoader {

    private Disposable mPublish;


    public interface OnPlayVideoCallback{

        /**
         * 购买记录
         * @param isPlay 是否已购买
         */
        void playVideoStatus(ResultMsg isPlay);

        void onFailure(Throwable e);

    }

    public void requestHistory(final String pToken, final int pAnchorId, int start, int num, @NonNull final LoaderManager.LoaderCallbacks<LiveHistoryComband> pCallback) {

        if (mPublish != null) {
            mPublish.dispose();
        }
        mPublish = Observable.create(new ObservableOnSubscribe<ResultBean>() {

            @Override
            public void subscribe(ObservableEmitter<ResultBean> pEmitter) throws Exception {

                LivePlayApi mApi = OkHttpModule.getInstance().getRetrofit().create(LivePlayApi.class);
                Call<String> call = mApi.getUserMoney(pToken);
                try {
                    Response<String> response = call.execute();
                    if (response.body() == null || response.body().equals("")) {
                        pEmitter.onNext(null);
                    }
                    ResultBean resultData = JSONObject.parseObject(response.body(), ResultBean.class);
                    if (resultData == null) {
                        pEmitter.onNext(null);
                    }
                    pEmitter.onNext(resultData);
                } catch (IOException e) {
                    e.printStackTrace();
                    pEmitter.onError(e);
                }
            }

        }).subscribeOn(Schedulers.newThread())
                .map(new Function<ResultBean, LiveHistoryComband>() {
                         @Override
                         public LiveHistoryComband apply(ResultBean resultBean) throws Exception {

                             LiveVideoListApi searchIndexApi = OkHttpModule.getInstance().getRetrofit().create(LiveVideoListApi.class);
                             Call<String> call = searchIndexApi.getHistory(pAnchorId, pToken, 0, 10);
                             try {
                                 Response<String> response = call.execute();
                                 if (response.body() == null || response.body().equals("")) {
                                     return null;
                                 }
                                 JsonResult<JSONArray> resultData = JSONObject.parseObject(response.body(), JsonResult.class);
                                 if (resultData == null) {
                                     return null;
                                 }
                                 JSONArray array = resultData.getData();
                                 List<LiveVideoBean> targetData = JSONObject.parseArray(array.toJSONString(), LiveVideoBean.class);
                                 if (targetData == null) {
                                     return null;
                                 }
                                 LiveHistoryComband comband=new LiveHistoryComband();
                                 comband.setLiveVideoBean(targetData);
                                 comband.setResultBean(resultBean);
                                 return comband;
                             } catch (IOException e) {
                                 e.printStackTrace();

                             }
                             return null;
                         }

                     }
                )
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<LiveHistoryComband>() {
                    @Override
                    public void accept(LiveHistoryComband playBean) throws Exception {
                        pCallback.onLoadFinished(null, playBean);
                        mPublish.dispose();
                    }
                });
    }

    /**
     * 查询是否购买该视频
     * @param pToken
     * @param pId
     */
    public void requestByPlayVideoStatus(final String pToken, final String pId, final OnPlayVideoCallback callback){


        Observable.create(new ObservableOnSubscribe<ResultMsg>() {

            @Override
            public void subscribe(ObservableEmitter<ResultMsg> pEmitter) throws Exception {

                LiveVideoListApi mApi = OkHttpModule.getInstance().getRetrofit().create(LiveVideoListApi.class);
                Call<String> call = mApi.requesVideoPlayStatus(pToken,pId);
                try {
                    Response<String> response = call.execute();
                    if (response.body() == null || response.body().equals("")) {
                        pEmitter.onNext(null);
                    }
                    ResultMsg resultData = JSONObject.parseObject(response.body(), ResultMsg.class);
                    if (resultData == null) {
                        pEmitter.onNext(null);
                    }
                    pEmitter.onNext(resultData);
                    pEmitter.onComplete();
                } catch (IOException e) {
                    e.printStackTrace();
                    pEmitter.onError(e);
                }
            }

        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResultMsg>(){

                    private Disposable mDisposable;

                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable=d;
                    }

                    @Override
                    public void onNext(ResultMsg resultMsg) {
                        callback.playVideoStatus(resultMsg);
                        mDisposable.dispose();
                    }

                    @Override
                    public void onError(Throwable e) {
                        callback.onFailure(e);
                        mDisposable.dispose();
                    }

                    @Override
                    public void onComplete() {
                        mDisposable.dispose();
                    }
                });

    }


    public void playVideo(final String pToken, final String pId, final String pMoney,final OnPlayVideoCallback callback){

        Observable.create(new ObservableOnSubscribe<ResultMsg>() {

            @Override
            public void subscribe(ObservableEmitter<ResultMsg> pEmitter) throws Exception {

                LivePlayApi mApi = OkHttpModule.getInstance().getRetrofit().create(LivePlayApi.class);
                Call<String> call = mApi.playVideo(pToken,pId,pMoney);
                try {
                    Response<String> response = call.execute();
                    if (response.body() == null || response.body().equals("")) {
                        pEmitter.onNext(null);
                    }
                    ResultMsg resultData = JSONObject.parseObject(response.body(), ResultMsg.class);
                    if (resultData == null) {
                        pEmitter.onNext(null);
                    }
                    pEmitter.onNext(resultData);
                    pEmitter.onComplete();
                } catch (IOException e) {
                    e.printStackTrace();
                    pEmitter.onError(e);
                }
            }

        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResultMsg>(){

                    private Disposable mDisposable;

                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable=d;
                    }

                    @Override
                    public void onNext(ResultMsg resultBean) {
                        callback.playVideoStatus(resultBean);
                        mDisposable.dispose();
                    }

                    @Override
                    public void onError(Throwable e) {
                        callback.onFailure(e);
                        mDisposable.dispose();
                    }

                    @Override
                    public void onComplete() {
                        mDisposable.dispose();
                    }
                });
    }

}
